import { Component, Prop, Watch } from 'vue-property-decorator';

import { EnumFieldOption } from '../../vendors/handie';

import BaseEnumFilterHeadlessWidget from './BaseEnumFilter';

@Component
export default class MultiEnumFilterHeadlessWidget extends BaseEnumFilterHeadlessWidget<
  number[] | string[]
> {
  @Prop({ type: Array, default: () => [] })
  protected readonly value!: number[] | string[];

  protected internalValue: number[] | string[] = [];

  private optionMap: Record<string, EnumFieldOption> = {};

  protected get displayText(): string {
    return ((this.value || []) as any[])
      .map(value => (value != null && this.optionMap[value] ? this.optionMap[value].label : value))
      .join('、');
  }

  @Watch('value', { immediate: true })
  private handleValueChange(): void {
    this.internalValue = this.value || [];
  }

  @Watch('options', { immediate: true })
  private handleOptionsChange(): void {
    this.optionMap = this.options.reduce((prev, opt) => ({ ...prev, [opt.value]: opt }), {});
  }
}
